﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEditor;
using UnityEngine;

namespace Game.System.EventSystem
{
    /// <summary>
    /// 事件处理器
    /// </summary>
    public static class GameEventManager
    {
        // Root事件组，管理游戏内的所有事件
        private static GameEventGroup m_root;
        public static GameEventGroup RootGroup
        {
            get
            {
                return m_root;
            }
            private set
            {
                m_root = value;
            }
        }

        // 储存事件数据的路径
        //public const string EventDataPath = "Assets/Resources/Data/EventData/EventCore/EventCore.asset";
        public const string EventDataPath = "Data/EventData/EventCore/EventCore";

        public struct NodeEvent
        {
            public EventWindow.SerializableNode node;
            public GameBaseEvent gameEvent;
        }

        static GameEventManager()
        {
            Init();
            MonoBehaviour.print("游戏事件系统初始化");
        }

        //  初始化
        private static void Init()
        {
            RootGroup = new GameEventGroup("Root");
            RootGroup.EnableAllEvent(true);
        }

        //从SO文件中读取事件系统配置
        public static void ImportDataFromGraph()
        {
            //var graph = AssetDatabase.LoadAssetAtPath<EventWindow.EventGraph>(EventDataPath);
            var graph = Resources.Load<EventWindow.EventGraph>(EventDataPath);
            var root = graph.nodes.Find(n => n.name == "Root");
            if (root == null)
            {
                Debug.LogError("无法找到根事件");
                return;
            }

            RootGroup = new GameEventGroup("Root");
            //BFS遍历
            Queue<NodeEvent> nodeQueue = new Queue<NodeEvent>();
            nodeQueue.Enqueue(new NodeEvent() { node = root, gameEvent = RootGroup });
            while (nodeQueue.Count > 0)
            {
                var node = nodeQueue.Dequeue();
                if (node.node != null && node.node.type == "Group" && node.node.children != null && node.node.children.Count > 0)
                {
                    for (int i = 0; i < node.node.children.Count; i++)
                    {
                        var child = graph.nodes.Find(n => n.id == node.node.children[i]);
                        if (child != null)
                        {
                            if (child.type == "Single")
                            {
                                var newEvent = new GameEvent(child.name);
                                ((GameEventGroup)node.gameEvent).AddEvent(newEvent);
                            }
                            else if (child.type == "Group")
                            {
                                var newEvent = new GameEventGroup(child.name);
                                ((GameEventGroup)node.gameEvent).AddEvent(newEvent);
                                nodeQueue.Enqueue(new NodeEvent() { node = child, gameEvent = newEvent });
                            }
                        }
                    }
                }
            }
            RootGroup.EnableAllEvent(true);
            Debug.Log("事件读取完成");
        }

        /// <summary>
        /// 注册事件
        /// </summary>
        /// <param name="eventName"></param>
        /// <param name="check"></param>
        public static void RegisterEvent(string eventName, GameEvent.CheckHandle check)
        {
            var target = RootGroup?.GetEvent(eventName);
            if (target != null && target is GameEvent tepm)
            {
                tepm.AddCheckHandle(check);
            }
        }
        /// <summary>
        /// 订阅事件
        /// </summary>
        /// <param name="eventName"></param>
        /// <param name="response"></param>
        public static void SubscribeEvent(string eventName, GameEvent.ResponseHandle response)
        {
            var target = RootGroup?.GetEvent(eventName);
            if (target != null && target is GameEvent tepm)
            {
                tepm.AddResponse(response);
            }
        }
        /// <summary>
        /// 启动禁用事件
        /// </summary>
        /// <param name="eventName"></param>
        /// <param name="_enable"></param>
        public static void EnableEvent(string eventName, bool _enable)
        {
            var target = RootGroup?.GetEvent(eventName);
            if (target != null)
            {
                target.enable = _enable;
            }
        }
        /// <summary>
        /// 启用禁用一个组的事件
        /// </summary>
        /// <param name="eventName">事件组名</param>
        /// <param name="_enable"></param>
        public static void EnableAllEvents(string eventName, bool _enable)
        {
            var target = RootGroup?.GetEvent(eventName) as GameEventGroup;
            if (target != null)
            {
                target.EnableAllEvent(_enable);
            }
        }

        //启用所有事件
        public static void EnableAllRootEvents(bool _enable)
        {
            RootGroup.EnableAllEvent(_enable);
        }

        /// <summary>
        /// 更新
        /// </summary>
        public static void Update()
        {
            if (RootGroup == null)
            {
                return;
            }
            RootGroup.Update();
        }
    }
    /// <summary>
    /// 用于不违反开闭原则添加功能
    /// </summary>
    public static class GameEventManagerExpansion
    {
        /// <summary>
        /// 添加事件
        /// </summary>
        /// <param name="eventName">事件组名</param>
        /// <param name="Event"></param>
        public static void AddEvent(string eventName, GameBaseEvent Event)
        {
            var target = GameEventManager.RootGroup?.GetEvent(eventName);
            if (target != null && target is GameEventGroup temp)
            {
                temp.AddEvent(Event);
            }
        }
        /// <summary>
        /// 注册一个组的事件
        /// </summary>
        /// <param name="eventName"></param>
        /// <param name="check"></param>
        public static void RegisterAllEvent(string eventName, GameEvent.CheckHandle check)
        {
            var target = GameEventManager.RootGroup?.GetEvent(eventName);
            if (target != null && target is GameEventGroup temp)
            {
                foreach (var item in temp.GetAllEvent())
                {
                    item.AddCheckHandle(check);
                }
            }
        }
        /// <summary>
        /// 订阅一个组的事件
        /// </summary>
        /// <param name="eventName"></param>
        /// <param name="response"></param>
        public static void SubscribeAllEvent(string eventName, GameEvent.ResponseHandle response)
        {
            var target = GameEventManager.RootGroup?.GetEvent(eventName);
            if (target != null && target is GameEventGroup temp)
            {
                foreach (var item in temp.GetAllEvent())
                {
                    item.AddResponse(response);
                }
            }
        }
    }
}
